#!/bin/bash

need_cmds=( git repo swift )
for cmds in "${need_cmds[@]}"; do
  if hash $cmds 2>/dev/null; then 
    echo "$cmds: `which $cmds`"
  else
    echo "no exists $cmds"
    exit
  fi
done

BASE_DIR=$(dirname $(dirname $(readlink -f "$0")))
echo $BASE_DIR

# ARK
ARK_PATH="./standalone/arkcompiler/"
ark_repos=( ets_runtime runtime_core toolchain ets_frontend )  
if [ ! -d "standalone" ]; then
  mkdir standalone; cd standalone;
  repo init -u https://gitee.com/ark-standalone-build/manifest.git -b master
else
  for ark_repo in "${ark_repos[@]}"; do
    if [ -d "$BASE_DIR/$ARK_PATH/$ark_repo/.git" ]; then
      cd "$BASE_DIR/$ARK_PATH/$ark_repo"
      git stash
    else
      echo "no .git in $BASE_DIR/$ARK_PATH/$ark_repo"
      exit
    fi
  done
fi

cd "$BASE_DIR/standalone"
repo sync -c
cd "$BASE_DIR"

for ark_repo in "${ark_repos[@]}"; do
  if [ -f "$BASE_DIR/patch/$ark_repo.diff" ]; then
    cd "$BASE_DIR/$ARK_PATH/$ark_repo"
    git apply "$BASE_DIR/patch/$ark_repo.diff"
  fi
done

if [ ! -L "$BASE_DIR/standalone/arkfuzzer" ]; then
  ln -s "$BASE_DIR/arkfuzzer" "$BASE_DIR/standalone/arkfuzzer"
fi

cd "$BASE_DIR/standalone"
./prebuilts_download.sh
python ark.py x64.release arkfuzzer

# Fuzzilli
cd "$BASE_DIR"
if [ ! -d "$BASE_DIR/fuzzilli" ]; then
  git clone https://github.com/googleprojectzero/fuzzilli.git
else
  if [ -d "$BASE_DIR/fuzzilli/.git" ]; then
    cd "$BASE_DIR/fuzzilli/"
    git stash
    git pull
  fi
fi

cd "$BASE_DIR/fuzzilli/"
git apply "$BASE_DIR/patch/fuzzilli.diff"